﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;

using ShoveEL.Database;

/// <summary>
/// Task 的摘要说明
/// </summary>
public class Task_SendEmail
{
    private string MailTo, Subject, Body;

    public Task_SendEmail(string mailTo, string subject, string body)
    {
        MailTo = mailTo;
        Subject = subject;
        Body = body;
    }

    public void Run()
    {
        lock (this) // 确保临界区被一个 Thread 所占用
        {
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Do));
            thread.IsBackground = true;

            thread.Start();
        }
    }

    public void Do()
    {
        System.Threading.Thread.Sleep(1000);

        string EmailServer_From = "", EmailServer_EmailServer = "", EmailServer_User = "", EmailServer_Password = "";

        try
        {
            EmailServer_From = PublicFunction.GetOptionsAsString("EmailServer_From");
            EmailServer_EmailServer = PublicFunction.GetOptionsAsString("EmailServer_EmailServer");
            EmailServer_User = PublicFunction.GetOptionsAsString("EmailServer_User");
            EmailServer_Password = PublicFunction.GetOptionsAsString("EmailServer_Password");
        }
        catch { }

        if ((EmailServer_From == "") || (EmailServer_EmailServer == "") || (EmailServer_User == ""))
        {
            PublicFunction.WriteLogini("Send Email: Read EmailServer configure fail.");

            return;
        }

        int TryNum = 0;
        int Result = -1;

        while ((Result < 0) && (TryNum++ < 3))
        {
            Result = ShoveEL._Net.Email.SendEmail(EmailServer_From, MailTo, Subject, Body, EmailServer_EmailServer, EmailServer_User, EmailServer_Password);
        }

        if (Result < 0)
        {
            DAL.Tables.T_WaitSendEmail.Insert(ShoveEL._String.Compress(MailTo), true, ShoveEL._String.Compress(Subject), true, ShoveEL._String.Compress(Body), true, false, true, 0, true);

            PublicFunction.WriteLogini("Send Email: Send Mail fail. Tryed: " + TryNum.ToString());
        }
        else
        {
            DAL.Tables.T_WaitSendEmail.Insert(ShoveEL._String.Compress(MailTo), true, ShoveEL._String.Compress(Subject), true, ShoveEL._String.Compress(Body), true, true, true, 1, true);
        }
    }
}